﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using System.Configuration;

using Castle.Core.Logging;

using InfoGenerateSystem.Core.Utils;
using InfoGenerateSystem.Domain;
using InfoGenerateSystem.Service.Interfaces;

using hxSec.StaticPage;
using System.Xml;

namespace InfoGenerateSystem.AppView
{
    /// <summary>
    /// 资讯生成系统主界面
    /// 
    /// 创建人:     王昊
    /// 创建时间:   2009-04-28
    /// 
    /// </summary>
    public partial class frmMain : Form
    {
        #region 资讯生成系统--导出Excel,网页截图部分 Author:王昊

        private ILogger _log = ServiceHelper.GetService(typeof(ILogger)) as ILogger;
        private IExcelToDatabase _excelService = ServiceHelper.GetService(typeof(IExcelToDatabase)) as IExcelToDatabase;
        private IWebPageToImage _snagService = ServiceHelper.GetService(typeof(IWebPageToImage)) as IWebPageToImage;
        private IDataSetToImage _imageService = ServiceHelper.GetService(typeof(IDataSetToImage)) as IDataSetToImage;

        Thread taExcel;
        Thread taSnag;
        Thread taImage;

        Hashtable htExcelRunnedTime = new Hashtable();
        Hashtable htSnagRunnedTime = new Hashtable();
        Hashtable htImageRunnedTime = new Hashtable();

        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            InitStyle();
            InitConfig();

            StartTimer();

            #region 第一版图表生成部分 Author:关鑫

            this.dom = null;
            this.inteval = "";
            this.errorcount = 0;
            this.BoolAppIsRunning = false;
            this.AppAutoRun = "";
            this.nowthreadCount = 0;

            this.LoadConfig();
            //notifyIcon.Icon = iconStop;
            if (AppAutoRun.CompareTo("1") == 0)
            {
                BoolNeedRun = true;
                timer1.Interval = 3000;
                timer1.Start();
            }
            else
            {
                BoolNeedRun = false;
            }

            //取消控件线程安全保护模式
            Control.CheckForIllegalCrossThreadCalls = false;

            try
            {
                this.iconRun = new Icon("ChartGenerator\\AppRun.ico");
                this.iconStop = new Icon("ChartGenerator\\AppStop.ico");
            }
            catch (Exception exception)
            {
                this.tbAutoInfo.AppendText(exception.ToString());
            }

            #endregion 第一版图表生成部分 Author:关鑫
        }

        //初始化Style
        private void InitStyle()
        {
            this.notifyIconMain.Visible = true;
            this.SizeChanged += new System.EventHandler(this.frmMain_SizeChanged);
        }

        //读取并装载所有配置
        private void InitConfig()
        {
            try
            {
                _excelService.Directory = Application.StartupPath;
                _excelService.ConfigFilePath = ConfigurationManager.AppSettings["ExcelLabelsConfigFilePath"];
                _snagService.Directory = Application.StartupPath;
                _snagService.ConfigFilePath = ConfigurationManager.AppSettings["SnagConfigFilePath"];
                _imageService.Directory = Application.StartupPath;
                _imageService.ConfigFilePath = ConfigurationManager.AppSettings["ImageExportConfigFilePath"];

                BindExcelReportPeriodComboBoxData();
                BindExcelLabelsListBoxData();
                BindSnagLabelslListBoxData();
                BindSnagUrlsListBoxData();
                BindImageLabelslListBoxData();
                LoadExcelExportConfig();
                LoadSnagConfig();
                LoadImageConfig();
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
                _log.Error(ex.StackTrace);
                MessageBox.Show(ex.Message, "程序配置错误或数据库连接异常");
            }
        }

        //重新读取并装载所有配置
        private void ReloadConfig()
        {
            ReloadExcelLabelsListBoxData();
            ReloadSnagLabelsListBoxData();
            ReloadSnagUrlsListBoxData();
            ReloadImageLabelsListBoxData();
            LoadExcelExportConfig();
            LoadSnagConfig();
            LoadImageConfig();
        }

        //定制最小化
        private void FormMinimize()
        {
            this.Hide();
            this.ShowInTaskbar = false;
        }

        //定制还原
        private void FormRestore()
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
            this.ShowInTaskbar = true;
        }

        //定制关闭
        private void ExitApplication()
        {
            this.notifyIconMain.Visible = false;

            Application.ExitThread();
            Application.Exit();
            Environment.Exit(1);
        }

        //关闭程序
        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            ExitApplication();
        }

        //绑定Excel报告期ComboBox
        private void BindExcelReportPeriodComboBoxData()
        {
            cbReportDate.DataSource = _excelService.GetReportPeriodList(12);
            cbReportDate.DisplayMember = "DisplayPeriod";
            cbReportDate.ValueMember = "ValueDate";
        }

        //绑定Excel标签ListBox
        private void BindExcelLabelsListBoxData()
        {
            try
            {
                lbExcelLabels.DataSource = null;
                lbExcelLabels.DataSource = _excelService.GetLabelList();
                lbExcelLabels.ValueMember = "SECID";
                lbExcelLabels.DisplayMember = "DisplayLabel";
            }
            catch (Exception ex)
            {
                throw new Exception("Config/ExcelExportConfig.ini文件标签配置错误，请重新配置");
            }
        }

        //绑定截图标签ListBox
        private void BindSnagLabelslListBoxData()
        {
            try
            {
                lbSnagLabels.DataSource = null;
                lbSnagLabels.DataSource = _snagService.GetLabelList();
                lbSnagLabels.ValueMember = "SECID";
                lbSnagLabels.DisplayMember = "DisplayLabel";
            }
            catch (Exception)
            {
                throw new Exception("Config/SnagConfig.ini文件标签配置错误，请重新配置");
            }
        }

        //绑定网页ListBox
        private void BindSnagUrlsListBoxData()
        {
            lbSnagUrl.DataSource = null;
            lbSnagUrl.DataSource = _snagService.GetWebPageList();
            lbSnagUrl.ValueMember = "Url";
            lbSnagUrl.DisplayMember = "Url";
        }

        //绑定表图生成标签ListBox
        private void BindImageLabelslListBoxData()
        {
            try
            {
                lbExportImageLabels.DataSource = null;
                lbExportImageLabels.DataSource = _imageService.GetLabelList();
                lbExportImageLabels.ValueMember = "SECID";
                lbExportImageLabels.DisplayMember = "DisplayLabel";
            }
            catch (Exception)
            {
                throw new Exception("Config/ImageExportConfig.ini文件标签配置错误，请重新配置");
            }
        }

        //重新装载数据并绑定Excel标签ListBox
        private void ReloadExcelLabelsListBoxData()
        {
            lbExcelLabels.DataSource = null;
            lbExcelLabels.DataSource = _excelService.ReloadLabelList();
            lbExcelLabels.ValueMember = "SECID";
            lbExcelLabels.DisplayMember = "DisplayLabel";
        }

        //重新装载数据并绑定截图标签ListBox
        private void ReloadSnagLabelsListBoxData()
        {
            lbSnagLabels.DataSource = null;
            lbSnagLabels.DataSource = _snagService.ReloadLabelList();
            lbSnagLabels.ValueMember = "SECID";
            lbSnagLabels.DisplayMember = "DisplayLabel";
        }

        //重新装载数据并绑定网页ListBox
        private void ReloadSnagUrlsListBoxData()
        {
            lbSnagUrl.DataSource = null;
            lbSnagUrl.DataSource = _snagService.ReloadWebPageList();
            lbSnagUrl.ValueMember = "Url";
            lbSnagUrl.DisplayMember = "Url";
        }

        //重新装载数据并绑定表图生成标签ListBox
        private void ReloadImageLabelsListBoxData()
        {
            lbExportImageLabels.DataSource = null;
            lbExportImageLabels.DataSource = _imageService.ReloadLabelList();
            lbExportImageLabels.ValueMember = "SECID";
            lbExportImageLabels.DisplayMember = "DisplayLabel";
        }

        //装载Excel导出配置
        private void LoadExcelExportConfig()
        {
            ExcelExportConfig eec = _excelService.GetExcelExportConfig();
            txtExcelStartTime.Text = eec.TimerStart.ToString("HH:mm");

            if (eec.RunningState == "Start")
            {
                rdoExcelStart.Checked = true;
            }
            else if (eec.RunningState == "Stop")
            {
                rdoExcelStop.Checked = true;
            }
        }

        //装载截图配置
        private void LoadSnagConfig()
        {
            SnagConfig sc = _snagService.GetSnagConfig();
            txtSnagStartTime.Text = sc.TimerStart.ToString("HH:mm");
            txtScrWidth.Text = Convert.ToString(sc.ScrWidth);
            txtScrHeight.Text = Convert.ToString(sc.ScrHeight);
            txtImageWidth.Text = Convert.ToString(sc.ImageWidth);
            txtImageHeight.Text = Convert.ToString(sc.ImageHeight);

            if (sc.RunningState == "Start")
            {
                rdoSnagStart.Checked = true;
            }
            else if (sc.RunningState == "Stop")
            {
                rdoSnagStop.Checked = true;
            }
        }

        //装载表图生成配置
        private void LoadImageConfig()
        {
            ExportImageConfig eic = _imageService.GetExportImageConfig();
            txtExportImageStartTime.Text = eic.TimerStart.ToString("HH:mm");

            if (eic.RunningState == "Start")
            {
                rdoExportImageStart.Checked = true;
            }
            else if (eic.RunningState == "Stop")
            {
                rdoExportImageStop.Checked = true;
            }
        }

        //应用所有配置
        private void SaveAll()
        {
            ExcelExportConfig eec = new ExcelExportConfig();
            eec.RunningState = rdoExcelStart.Checked ? "Start" : "Stop";
            eec.TimerStart = Convert.ToDateTime(txtExcelStartTime.Text);
            IList<TblbLabel> excelLabelList = _excelService.GetLabelList();
            _excelService.SaveExcelExportConfig(eec, excelLabelList);

            SnagConfig sc = new SnagConfig();
            sc.RunningState = rdoSnagStart.Checked ? "Start" : "Stop";
            sc.TimerStart = Convert.ToDateTime(txtSnagStartTime.Text);
            sc.ScrWidth = Convert.ToInt32(txtScrWidth.Text);
            sc.ScrHeight = Convert.ToInt32(txtScrHeight.Text);
            sc.ImageWidth = Convert.ToInt32(txtImageWidth.Text);
            sc.ImageHeight = Convert.ToInt32(txtImageHeight.Text);
            IList<TblbLabel> snagLabelList = _snagService.GetLabelList();
            IList<ImageWebPage> webPageList = _snagService.GetWebPageList();
            _snagService.SaveSnagConfig(sc, snagLabelList, webPageList);


            ExportImageConfig eic = new ExportImageConfig();
            eic.RunningState = rdoExportImageStart.Checked ? "Start" : "Stop";
            eic.TimerStart = Convert.ToDateTime(txtExportImageStartTime.Text);
            eic.ImagePercent = Convert.ToInt32(txtImagePercent.Text);
            IList<TblbLabel> imageLabelList = _imageService.GetLabelList();
            _imageService.SaveExportImageConfig(eic, imageLabelList);
        }

        //计时器开始
        private void StartTimer()
        {
            tmrExcelExporter.Interval = 30 * 1000;
            tmrExcelExporter.Enabled = true;
            tmrExcelExporter.Start();

            tmrSnagWeb.Interval = 30 * 1000;
            tmrSnagWeb.Enabled = true;
            tmrSnagWeb.Start();

            tmrImageExporter.Interval = 30 * 1000;
            tmrImageExporter.Enabled = true;
            tmrImageExporter.Start();
        }

        //导出Excel
        private void GoExportExcel()
        {
            Hashtable htParams = new Hashtable();
            htParams["JZRQ"] = cbReportDate.SelectedValue;
            _excelService.ExcelProcedureParams = htParams;

            //WaitCallback w = new WaitCallback(_excelService.InsertExcel);
            //ThreadPool.QueueUserWorkItem(w);

            btnGoExportExcel.Enabled = false;
            taExcel = new Thread(new ThreadStart(delegate()
            {
                _excelService.GoExportExcel();
            }));
            taExcel.Start();

            //excelMethod.BeginInvoke(new AsyncCallback(ExcelTaskFinished), null);

            StartTimer();
        }
        //delegate void GoExcelMethod();
        //static GoExcelMethod excelMethod = new GoExcelMethod(_excelService.InsertExcel);
        //public void ExcelTaskFinished(IAsyncResult result)
        //{
        //    btnGoExportExcel.Enabled = true;
        //}

        //网页截图
        private void GoSnagWeb()
        {
            btnGoSnagWeb.Enabled = false;
            taSnag = new Thread(new ThreadStart(delegate()
            {
                //_snagService.GoSnagImage();
            }));
            taSnag.SetApartmentState(ApartmentState.STA);
            taSnag.Start();

            //snapMethod.BeginInvoke(new AsyncCallback(SnapTaskFinished), null);

            StartTimer();
        }
        //delegate void GoSnapMethod();
        //static GoSnapMethod snapMethod = new GoSnapMethod(_snagService.GoSnapImage);
        //public void SnapTaskFinished(IAsyncResult result)
        //{
        //    //btnGoSnagWeb.Enabled = true;
        //}

        //表图生成
        private void GoExportImage()
        {
            btnGoExportImage.Enabled = false;

            taImage = new Thread(new ThreadStart(delegate()
            {
                _imageService.GoExportImage();
            }));
            taImage.Start();

            StartTimer();
        }

        //导出Excel计时器
        private void tmrExcelExporter_Tick(object sender, EventArgs e)
        {
            if (!htExcelRunnedTime.Contains(DateTime.Now.ToString("yyyy-MM-dd-HH-mm")))
            {
                if (txtExcelStartTime.Text.Trim() == DateTime.Now.ToString("HH:mm"))
                {
                    GoExportExcel();
                    htExcelRunnedTime[DateTime.Now.ToString("yyyy-MM-dd-HH-mm")] = 1;
                }
            }

            if (taExcel != null)
            {
                if (taExcel.ThreadState == ThreadState.Stopped)
                {
                    //FinishedExcel();
                    btnGoExportExcel.Enabled = true;
                }
            }
            else
                btnGoExportExcel.Enabled = true;
            //if (_excelService.ThreadCount == 0) 
            //{
            //    taExcel.Abort();
            //    btnGoExportExcel.Enabled = true;
            //}
        }
        //private void FinishedExcel()
        //{
        //    Thread taDelExcel = new Thread(new ThreadStart(delegate()
        //    {
        //        DateTime time = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd ") + txtExcelStartTime.Text.Trim());
        //        _excelService.DeleteBeforeRecords(time);
        //    }));
        //    taDelExcel.Start();
        //}

        //网页截图计时器
        private void tmrSnagWeb_Tick(object sender, EventArgs e)
        {
            if (!htSnagRunnedTime.Contains(DateTime.Now.ToString("yyyy-MM-dd-HH-mm")))
            {
                if (txtSnagStartTime.Text.Trim() == DateTime.Now.ToString("HH:mm"))
                {
                    GoSnagWeb();
                    htSnagRunnedTime[DateTime.Now.ToString("yyyy-MM-dd-HH-mm")] = 1;
                }
            }

            if (taSnag != null)
            {
                if (taSnag.ThreadState == ThreadState.Stopped)
                {
                    btnGoSnagWeb.Enabled = true;
                }
            }
            else
            {
                btnGoSnagWeb.Enabled = true;
            }
        }

        //表图生成计时器

        private void tmrImageExporter_Tick(object sender, EventArgs e)
        {
            if (!htImageRunnedTime.Contains(DateTime.Now.ToString("yyyy-MM-dd-HH-mm")))
            {
                if (txtExportImageStartTime.Text.Trim() == DateTime.Now.ToString("HH:mm"))
                {
                    GoExportImage();

                    htImageRunnedTime[DateTime.Now.ToString("yyyy-MM-dd-HH-mm")] = 1;
                }
            }
            if (taImage != null)
            {
                if (taImage.ThreadState == ThreadState.Stopped)
                {
                    //FinishedImage();
                    btnGoExportImage.Enabled = true;
                }
            }
            else
                btnGoExportImage.Enabled = true;
            //if (_imageService.ThreadCount == 0) 
            //{
            //    taImage.Abort();
            //    btnGoExportImage.Enabled = true;
            //}
        }
        //private void FinishedImage()
        //{
        //    Thread taDelImage = new Thread(new ThreadStart(delegate()
        //    {
        //        DateTime time = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd ") + txtExportImageStartTime.Text.Trim());
        //        _imageService.DeleteBeforeRecords(time);
        //    }));
        //    taDelImage.Start();
        //}

        //导出Excel开关
        private void rdoExcelStart_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoExcelStart.Checked)
            {
                tmrExcelExporter.Enabled = true;
                tmrExcelExporter.Start();
                gbExcelTime.Enabled = true;
            }
        }
        private void rdoExcelStop_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoExcelStop.Checked)
            {
                tmrExcelExporter.Stop();
                tmrExcelExporter.Enabled = false;
                gbExcelTime.Enabled = false;
            }
        }

        //网页截图开关
        private void rdoSnagStart_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoSnagStart.Checked)
            {
                tmrSnagWeb.Enabled = true;
                tmrSnagWeb.Start();
                gbSnagTime.Enabled = true;
            }
        }
        private void rdoSnagStop_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoSnagStop.Checked)
            {
                tmrSnagWeb.Stop();
                tmrSnagWeb.Enabled = false;
                gbSnagTime.Enabled = false;
            }
        }

        //表图生成标签
        private void rdoExportImageStart_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoExportImageStart.Checked)
            {
                tmrImageExporter.Enabled = true;
                tmrImageExporter.Start();
                gbExportImageTime.Enabled = true;
            }
        }
        private void rdoExportImageStop_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoExportImageStop.Checked)
            {
                tmrImageExporter.Stop();
                tmrImageExporter.Enabled = false;
                gbExportImageTime.Enabled = false;
            }
        }

        //新增Excel标签
        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(txtExcelLabelAdd.Text.Trim()))
            {
                TblbLabel lbl = _excelService.GetLabelByID(Convert.ToInt64(txtExcelLabelAdd.Text));
                if (lbl != null)
                {
                    _excelService.GetLabelList().Add(lbl);

                    BindExcelLabelsListBoxData();
                    txtExcelLabelAdd.Text = String.Empty;
                }
                else { MessageBox.Show("所添加标签不存在。"); }
            }
        }

        //删除Excel标签
        private void btnDelete_Click(object sender, EventArgs e)
        {
            foreach (TblbLabel lbl in lbExcelLabels.SelectedItems)
            {
                _excelService.GetLabelList().Remove(lbl);
            }

            BindExcelLabelsListBoxData();
        }

        //新增截图标签
        private void btnSnagLabelAdd_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(txtSnagLabelAdd.Text.Trim()))
            {
                TblbLabel lbl = _snagService.GetLabelByID(Convert.ToInt64(txtSnagLabelAdd.Text));
                if (lbl != null)
                {
                    _snagService.GetLabelList().Add(lbl);

                    BindSnagLabelslListBoxData();
                    txtSnagLabelAdd.Text = String.Empty;
                }
                else { MessageBox.Show("所添加标签不存在。"); }
            }
        }

        //删除截图标签
        private void btnSnagLabelDelete_Click(object sender, EventArgs e)
        {
            foreach (TblbLabel lbl in lbSnagLabels.SelectedItems)
            {
                _snagService.GetLabelList().Remove(lbl);
            }

            BindSnagLabelslListBoxData();
        }

        //新增截图网址
        private void btnSangUrlAdd_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(txtSnagUrlAdd.Text.Trim()))
            {
                ImageWebPage webPage = new ImageWebPage();
                webPage.Url = txtSnagUrlAdd.Text.Trim();
                _snagService.GetWebPageList().Add(webPage);

                BindSnagUrlsListBoxData();
                txtSnagUrlAdd.Text = String.Empty;
            }
        }

        //删除截图网址
        private void btnSnagUrlDelete_Click(object sender, EventArgs e)
        {
            foreach (ImageWebPage webPage in lbSnagUrl.SelectedItems)
            {
                _snagService.GetWebPageList().Remove(webPage);
            }

            BindSnagUrlsListBoxData();
        }

        //新增表图生成标签
        private void btnExportImageLabelAdd_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(txtExportImageLabelAdd.Text.Trim()))
            {
                TblbLabel lbl = _imageService.GetLabelByID(Convert.ToInt64(txtExportImageLabelAdd.Text));
                if (lbl != null)
                {
                    _imageService.GetLabelList().Add(lbl);

                    BindImageLabelslListBoxData();
                    txtExportImageLabelAdd.Text = String.Empty;
                }
                else { MessageBox.Show("所添加标签不存在。"); }
            }
        }

        //删除表图生成标签
        private void btnExportImageLabelDelete_Click(object sender, EventArgs e)
        {
            foreach (TblbLabel lbl in lbExportImageLabels.SelectedItems)
            {
                _imageService.GetLabelList().Remove(lbl);
            }

            BindImageLabelslListBoxData();
        }

        private void btnGoExportExcel_Click(object sender, EventArgs e)
        {
            GoExportExcel();
        }

        private void btnGoSnagWeb_Click(object sender, EventArgs e)
        {
            GoSnagWeb();
        }

        private void btnGoExportImage_Click(object sender, EventArgs e)
        {
            GoExportImage();
        }

        //OK
        private void btnOK_Click(object sender, EventArgs e)
        {
            SaveAll();
            FormMinimize();
        }

        //Cancel
        private void btnCancel_Click(object sender, EventArgs e)
        {
            ReloadConfig();
            FormMinimize();
        }

        //Apply
        private void btnApply_Click(object sender, EventArgs e)
        {
            SaveAll();
        }

        private void frmMain_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                FormMinimize();
            }
        }

        private void notifyIconMain_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                FormRestore();
            }
        }

        private void tsmiOpenMain_Click(object sender, EventArgs e)
        {
            FormRestore();
        }

        private void tsmiExit_Click(object sender, EventArgs e)
        {
            ExitApplication();
        }

        #endregion 资讯生成系统--导出Excel,网页截图部分 Author:王昊

        #region 第一版图表生成部分 Author:关鑫
        // 创建回调函数代理
        //delegate void SetCallback(DataRow row);

        private System.Drawing.Icon iconRun;
        private System.Drawing.Icon iconStop;
        private string inteval = "";
        private string intevalToDB = "";
        private string PublicPageInfo = "<!--www.gazxfe.com," + DateTime.Now.ToString() + ",system-->\r\n";
        private int errorcount = 0;

        private bool BoolAppIsRunning = false;  //是否正在运行
        private bool BoolNeedRun = false;       //是否需要运行

        private string AppAutoRun;
        private string AppAutoRunByTime;
        private string chartFormat;

        private System.Xml.XmlDocument dom = null;
        private DataTable dtList;
        private DataTable dt;
        //private DataTable dtLabel;
        private DataTable tempData;
        private int nowthreadCount;
        private int threadCount;
        private int eachCustomerCount;
        private int waitCustomerCount;
        //private int finishCustomerCount;
        private int AppRunCount = 0;
        private int startRecord = 0;

        ChartData chartData = new ChartData();
        ChartHandler handler = new ChartHandler();
        public ChartQueue queue = new ChartQueue();

        #region 载入配置及初始化 datatable
        private void LoadConfig()
        {
            dom = new XmlDocument();
            string filename = Application.StartupPath + @"\ChartGenerator\Config.xml";
            dom.Load(filename);
            AppAutoRun = dom.SelectSingleNode("//AppAutoRun").InnerText;
            AppAutoRunByTime = dom.SelectSingleNode("//AppAutoRunByTime").InnerText;
            chartFormat = dom.SelectSingleNode("//chartFormat").InnerText;
            inteval = dom.SelectSingleNode("//inteval").InnerText;
            intevalToDB = dom.SelectSingleNode("//intevalToDB").InnerText;
            threadCount = int.Parse(dom.SelectSingleNode("//threadCount").InnerText);
            eachCustomerCount = int.Parse(dom.SelectSingleNode("//eachCustomerCount").InnerText);

            this.dt = new DataTable();
            this.dt.Columns.Add(new DataColumn("LABELID"));
            this.dt.Columns.Add(new DataColumn("RELACODE"));
            this.dt.Columns.Add(new DataColumn("RELANAME"));
            this.dt.Columns.Add(new DataColumn("LABELTYPE"));
            this.dt.Columns.Add(new DataColumn("WIDTH"));
            this.dt.Columns.Add(new DataColumn("HEIGHT"));
            this.dt.Columns.Add(new DataColumn("CHARTSTYLE"));
            this.dt.Columns.Add(new DataColumn("LABELNAME"));
            this.dt.Columns.Add(new DataColumn("GRAPHYID"));
            this.dt.Columns.Add(new DataColumn("OPERATIONDATE"));
            this.tempData = new DataTable();
            this.tempData.Columns.Add(new DataColumn("LABELID"));
            this.tempData.Columns.Add(new DataColumn("RELACODE"));
            this.tempData.Columns.Add(new DataColumn("RELANAME"));
            this.tempData.Columns.Add(new DataColumn("LABELTYPE"));
            this.tempData.Columns.Add(new DataColumn("WIDTH"));
            this.tempData.Columns.Add(new DataColumn("HEIGHT"));
            this.tempData.Columns.Add(new DataColumn("CHARTSTYLE"));
            this.tempData.Columns.Add(new DataColumn("LABELNAME"));
            this.tempData.Columns.Add(new DataColumn("GRAPHYID"));
            this.tempData.Columns.Add(new DataColumn("OPERATIONDATE"));
            this.dtList = new DataTable();
            this.dtList.Columns.Add(new DataColumn("ID"));
            this.dtList.Columns.Add(new DataColumn("TYPE"));
            this.dtList.Columns.Add(new DataColumn("ADDRESS"));

            XmlNodeList Addresses = dom.SelectNodes("//Addresses//Address");
            foreach (XmlNode node in Addresses)
            {
                DataRow row = dtList.NewRow();
                row[0] = node.Attributes["id"].Value;
                row[1] = node.Attributes["type"].Value;
                row[2] = node.InnerText;
                dtList.Rows.Add(row);
            }
        }
        #endregion

        #region 循环处理动态转静态
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (timer1.Interval != Convert.ToInt32(inteval) * 1000)
            {
                timer1.Interval = Convert.ToInt32(inteval) * 1000;
            }
            if (BoolNeedRun)
            {
                if (!BoolAppIsRunning)
                {
                    BoolAppIsRunning = true;
                    btnClick.Enabled = false;
                    //notifyIcon.Icon = iconRun;                   
                    timer1.Start();
                    object obj = this.errorcount;
                    Monitor.Enter(obj);
                    this.errorcount = 0;
                    Monitor.Exit(obj);
                    FnDrawChart2Model();
                    startRecord++;
                    if (dt == null || dt.Rows.Count <= 0)
                        BoolAppIsRunning = false;
                }
            }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            if (!BoolNeedRun)
            {
                timer2.Stop();
            }

            if ((BoolAppIsRunning) && (dt.Rows.Count > 0))
            {
                AddTreadPool();
            }
            else
            {
                if (nowthreadCount == 0)
                {
                    BoolAppIsRunning = false;
                    timer2.Stop();
                    tbAutoInfo.AppendText("\r\n－－－" + DateTime.Now.ToString() + "本轮账户图表生成结束－－－");
                    AppRunCount += 1;
                }
            }
        }

        #endregion

        // 对线程池的处理
        private void AddTreadPool()
        {
            if (BoolAppIsRunning)
            {
                try
                {
                    int num2;
                    int num3;
                    int count = dt.Rows.Count;
                    ThreadPool.GetAvailableThreads(out num3, out num2);
                    if (count >= threadCount)//当前剩余处理数>=总运行数量
                    {
                        count = threadCount;
                    }
                    if (count > num2)
                    {
                        count = num2;
                    }
                    int num4 = 0;

                    while (((dt.Rows.Count > 0) && (num4 <= count)) && (nowthreadCount <= threadCount))
                    {
                        Monitor.Enter(dt);
                        DataRow row = dt.Rows[0];
                        Monitor.Enter(tempData);
                        DataRow row2 = tempData.NewRow();
                        for (int i = 0; i < row.Table.Columns.Count; i++)
                        {
                            row2[i] = row[i].ToString();
                        }
                        tempData.Rows.Add(row2);
                        dt.Rows.RemoveAt(0);
                        Monitor.Exit(tempData);
                        Monitor.Exit(dt);
                        if (!ThreadPool.QueueUserWorkItem(new WaitCallback(DealRows), row2))
                        {
                            Thread.Sleep(800);
                            return;
                        }
                    }
                }
                catch (Exception exception)
                {
                    tbAutoInfo.AppendText("\r\n－－" + DateTime.Now.ToString() + " 调用线程池出错 \r\n" + exception.ToString());
                    WriteLog("\r\n－－" + DateTime.Now.ToString() + " 调用线程池出错\r\n" + exception.ToString());

                    Monitor.Exit(tempData);
                    Monitor.Exit(dt);
                }
            }
        }

        /// <summary>
        /// 生成图表执行按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClick_Click(object sender, EventArgs e)
        {
            btnClick.Enabled = false;
            btnPAUSE.Enabled = true;
            BoolNeedRun = true;
            //notifyIcon.Icon = iconRun;
            //Form.ActiveForm.Icon = iconRun;
            BoolAppIsRunning = true;
            timer3.Start();
            FnChart2DB();
            timer1.Start();
            FnDrawChart2Model();
        }

        /// <summary>
        /// 生成图表暂停按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPAUSE_Click(object sender, EventArgs e)
        {
            btnClick.Enabled = true;
            btnPAUSE.Enabled = false;
            BoolNeedRun = false;
            BoolAppIsRunning = false;
            timer1.Stop();
            timer3.Stop();
            //notifyIcon.Icon = iconStop;
            //Form.ActiveForm.Icon = iconStop;
        }

        // 需要画标签图的客户信息加载
        private void FnDrawChart2Model()
        {
            bool flag;
            //Monitor.Enter(this.dtLabel);
            try
            {
                this.dt = chartData.GetWaitTreatCustomerInfo(startRecord, eachCustomerCount);
                //this.dt = chartData.GetChartLabelData(0);              
                this.waitCustomerCount = this.dt.Rows.Count;
                if (waitCustomerCount > 0)
                {
                    this.tbAutoInfo.AppendText("\r\n－－" + DateTime.Now.ToString() + " 装载客户列表与标签列表成功,即将开始处理－－");
                    this.lbWaitCount.Text = waitCustomerCount.ToString() + " 个";
                    flag = true;
                }
                else
                {
                    if (this.tbAutoInfo.Lines.Length > 10)
                        this.tbAutoInfo.Clear();

                    if (this.tbToDBInfo.Lines.Length > 10)
                        this.tbToDBInfo.Clear();

                    this.tbAutoInfo.AppendText("\r\n－－" + DateTime.Now.ToString() + " 没有要处理客户,等待下次轮询－－");
                    startRecord = -1;
                    flag = false;
                }
            }
            catch (Exception exception)
            {
                this.tbAutoInfo.AppendText("\r\n－－" + exception.ToString());
                flag = false;
            }
            finally
            {
                //Monitor.Exit(this.dtLabel);
            }
            if (flag)
            {
                if (AppRunCount > 1)
                {
                    this.tbAutoInfo.Text = "";
                    AppRunCount = 0;
                }

                this.tbAutoInfo.AppendText("\r\n－－" + DateTime.Now.ToString() + " 装载客户列表成功,本轮生成开始－－");
                progressBar.Minimum = 0;
                progressBar.Maximum = dt.Rows.Count - 1;
                progressBar.Value = 0;
                progressBar.Step = 1;
                timer3.Start();
                AddTreadPool();
                timer2.Start();
            }
        }

        // 生成图表回调函数
        private void DealRows(object odr)
        {
            try
            {
                Monitor.Enter(tempData);
                DataRow row = (DataRow)odr;
                //this.tempData.Rows.Remove(row);
                Monitor.Exit(this.tempData);

                //this.tbAutoInfo.AppendText("\r\n－－" + DateTime.Now.ToString() + " 客户号：" + account + "(" + name + "), 正在处理中...");

                FnCreateAccountChartFile(row);
            }
            catch (Exception exception)
            {
                this.tbAutoInfo.AppendText("\r\n" + exception.ToString());
            }
            finally
            {
                progressBar.PerformStep();
                //this.finishCustomerCount = this.waitCustomerCount - dt.Rows.Count;
                //this.lbFinishCount.Text = finishCustomerCount.ToString() + " 个";
                object obj = this.nowthreadCount;
                Monitor.Enter(obj);
                this.nowthreadCount--;
                if (this.nowthreadCount < 0)
                {
                    this.nowthreadCount = 0;
                }
                Monitor.Exit(obj);
            }
        }

        #region 生成图表文件部分

        /// <summary>
        /// 开始创建图表文件
        /// </summary>
        /// <param name="account"></param>
        /// <param name="name"></param>
        /// <param name="dtLabel"></param>
        /// <returns></returns>
        private void FnCreateAccountChartFile(DataRow row)
        {
            string LABELID = string.Empty;
            string RELACODE = string.Empty;
            string RELANAME = string.Empty;
            string LABELTYPE = string.Empty;
            string WIDTH = string.Empty;
            string HEIGHT = string.Empty;
            string CHARTSTYLE = string.Empty;
            string LABELNAME = string.Empty;
            string GRAPHYID = string.Empty;
            try
            {
                LABELID = row["LABELID"].ToString();
                RELACODE = row["RELACODE"].ToString();
                RELANAME = row["RELANAME"].ToString();
                LABELTYPE = row["LABELTYPE"].ToString();
                WIDTH = row["WIDTH"].ToString();
                HEIGHT = row["HEIGHT"].ToString();
                CHARTSTYLE = row["CHARTSTYLE"].ToString();
                LABELNAME = row["LABELNAME"].ToString();
                GRAPHYID = row["GRAPHYID"].ToString();

                this.tbAutoInfo.AppendText("\r\n－－" + DateTime.Now.ToString() + " 客户号：" + RELACODE + " 在生成 " + LABELNAME + "图...");

                if (CHARTSTYLE == "0")
                {
                    FnListChartToDB(GRAPHYID, RELACODE, LABELID, LABELNAME, Convert.ToInt32(WIDTH), Convert.ToInt32(HEIGHT), chartFormat);
                }
                else
                {
                    try
                    {
                        byte[] bytes = handler.DrawChart(CHARTSTYLE, RELACODE, LABELID, chartFormat, Convert.ToInt32(WIDTH), Convert.ToInt32(HEIGHT), "");
                        if (bytes != null && bytes != new byte[0])
                        {
                            GraphyDataInfo graphyData = new GraphyDataInfo();
                            #region Init Model
                            graphyData.ACCOUNTCODE = Convert.ToInt64(RELACODE);
                            graphyData.GRAPHYID = Convert.ToInt64(GRAPHYID);
                            graphyData.FILENAME = RELACODE + "_" + LABELID + "_" + DateTime.Now.ToString("yyyyMMddhhmmss") + "." + this.chartFormat;
                            graphyData.LABELID = Convert.ToInt64(LABELID);
                            graphyData.LABELNAME = LABELNAME;
                            #endregion
                            graphyData.NR = bytes;
                            graphyData.OPERATIONDATE = DateTime.Now.ToString();
                            queue.Push(graphyData);
                            this.tbAutoInfo.AppendText("\r\n－－" + DateTime.Now.ToString() + " 客户号：" + RELACODE + " 生成 " + RELANAME + "图已完毕");
                            chartData.UpdateControlState(GRAPHYID, LABELID);
                        }
                        else if (bytes == new byte[0])
                            chartData.UpdateControlState(GRAPHYID, LABELID);
                        else if (bytes == null)
                            chartData.UpdateControlTimes(GRAPHYID, LABELID);
                    }
                    catch (Exception ex)
                    {
                        chartData.UpdateControlTimes(GRAPHYID, LABELID);
                        this.WriteLog("\r\n－－" + ex.Message);
                    }
                }
            }
            catch (Exception exception)
            {
                object obj = this.errorcount;
                Monitor.Enter(obj);
                this.errorcount++;
                Monitor.Exit(obj);
                this.tbAutoInfo.AppendText("\r\n－－" + DateTime.Now.ToString() + " 客户号：" + RELACODE + " 在生成 " + LABELNAME + " 时出错，错误信息为：\r\n" + exception.ToString());
                this.WriteLog("\r\n－－" + DateTime.Now.ToString() + " 客户号：" + RELACODE + " 在生成 " + LABELNAME + " 时出错，错误信息为：\r\n" + exception.ToString());
            }
        }
        #endregion

        #region 托盘相应功能

        // 窗体关闭事件
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {

        }

        #endregion

        // 写执行日志
        public void WriteLog(string logMessage)
        {
            string path = Application.StartupPath + @"\log" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
            try
            {
                StreamWriter writer = File.AppendText(path);
                writer.Write(logMessage);
                writer.Flush();
                writer.Close();
            }
            catch
            {
                if (!File.Exists(path))
                {
                    File.Create(path).Close();
                }
                else
                {
                    File.SetAttributes(path, FileAttributes.Normal);
                }
            }
        }

        private void TSMItemHx_Click(object sender, EventArgs e)
        {
            WindowState = FormWindowState.Minimized;
            Hide();
        }

        private void notifyIcon_DoubleClick(object sender, EventArgs e)
        {
            Show();
            WindowState = FormWindowState.Normal;
            Activate();
            Focus();
        }

        // 保存自动化程序设置
        private void btnSaveSet_Click(object sender, EventArgs e)
        {

        }

        // 处理图表入库轮询
        private void timer3_Tick(object sender, EventArgs e)
        {
            timer3.Interval = Convert.ToInt32(intevalToDB);

            timer3.Start();
            object obj = this.errorcount;
            Monitor.Enter(obj);
            this.errorcount = 0;
            Monitor.Exit(obj);
            FnChart2DB();
        }

        // 排队将图表插入数据库
        private void FnChart2DB()
        {
            string errorinfo = "";
            Monitor.Enter(queue);
            try
            {
                while (queue != null && queue.Count > 0)
                {
                    GraphyDataInfo data = (GraphyDataInfo)queue.Pop();
                    if (chartData.InsertChartToDB(data, out errorinfo))
                        this.tbToDBInfo.AppendText("\r\n－－" + DateTime.Now.ToString() + " 客户号：" + data.ACCOUNTCODE.ToString() + " 的 " + data.LABELNAME + "图已入库");
                    else
                    {
                        this.tbToDBInfo.AppendText("\r\n－－" + DateTime.Now.ToString() + " 客户号：" + data.ACCOUNTCODE.ToString() + " 的 " + data.LABELNAME + " 入库时出错，错误信息为：\r\n" + errorinfo);
                        this.WriteLog("\r\n－－" + DateTime.Now.ToString() + " 客户号：" + data.ACCOUNTCODE.ToString() + " 的 " + data.LABELNAME + " 入库时出错，错误信息为：\r\n" + errorinfo);
                    }
                }
            }
            catch (Exception exception)
            {
                this.tbToDBInfo.AppendText("\r\n－－" + exception.ToString());
                this.WriteLog("\r\n－－" + exception.ToString());
            }
            finally
            {
                Monitor.Exit(queue);
            }
        }

        public void FnListChartToDB(string id, string account, string labelid, string labelname, int width, int height, string format)
        {
            try
            {
                bool b = false;
                string address = string.Empty;
                foreach (DataRow row in this.dtList.Select("ID=" + labelid))
                {
                    if (row["TYPE"].ToString().Equals(""))
                        return;
                    else if (row["TYPE"].ToString().Equals("0"))
                        b = true;
                    else if (row["TYPE"].ToString().Equals("1"))
                        b = chartData.IsHoldByStockType("STOCK", account);
                    else if (row["TYPE"].ToString().Equals("2"))
                        b = chartData.IsHoldByStockType("FUND", account);
                    else
                        return;

                    if (b)
                    {
                        address = row["ADDRESS"].ToString();
                        string url = "http://" + "localhost/hxzq/Chart/" + address + ".aspx";
                        string filename = account + "_" + labelid.ToString() + "_" + DateTime.Now.ToString("yyyyMMddhhmmss") + "." + format;
                        //frmBrowser browser = new frmBrowser(url, account, Convert.ToInt32(id), labelid, labelname, width, height, filename, format, this);

                        //browser.Visible = false;
                        //browser.Hide();
                    }
                }
            }
            catch (Exception ex)
            {
                this.tbAutoInfo.AppendText("\r\n－－" + ex.Message);
                this.WriteLog("\r\n－－" + ex.Message);
            }
        }
        #endregion 第一版图表生成部分 Author:关鑫
    }
}
